package com.joysuch.wwyt.bp.service.impl;

import cn.zlg.common.util.CollectionUtils;
import com.joysuch.wwyt.bp.bean.inspect.BpInspectTypeBean;
import com.joysuch.wwyt.bp.entity.inspect.BpInspectType;
import com.joysuch.wwyt.bp.repository.BpInspectPlanRepository;
import com.joysuch.wwyt.bp.repository.BpInspectTypeRepository;
import com.joysuch.wwyt.bp.service.BpInspectTypeService;
import com.joysuch.wwyt.core.common.ajax.ResultBean;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;
import java.util.List;

@Slf4j
@Service
@Transactional
public class BpInspectTypeServiceImpl implements BpInspectTypeService {

    @Autowired
    private BpInspectTypeRepository bpInspectTypeRepository;
    @Autowired
    private BpInspectPlanRepository bpInspectPlanRepository;


    @Override
    public ResultBean save(BpInspectTypeBean bean) {
        String name = bean.getName();
        Long id = bean.getId();
        List<BpInspectType> list = bpInspectTypeRepository.findByName(name);

        BpInspectType entity;
        //新增保存
        if (id == null) {
            if (!CollectionUtils.isEmpty(list)) return ResultBean.fail(101, "此类型已存在");
            entity = new BpInspectType();
        } else {
            //修改保存
            entity = bpInspectTypeRepository.findById(id).get();
            if (name.equals(entity.getName())) return ResultBean.defaultSuccessResult();
            if (!CollectionUtils.isEmpty(list)) return ResultBean.fail(101, "此类型已存在");
        }
        entity.setName(bean.getName());
        bpInspectTypeRepository.save(entity);
        return ResultBean.success("操作成功");
    }

    @Override
    public void deleteById(Long id) {
        bpInspectTypeRepository.deleteById(id);
    }

    @Override
    public ResultBean list(Pageable pageable) {
        if (pageable.getPageSize() == 20) {
            List<BpInspectType> all = bpInspectTypeRepository.findAll();
            for (BpInspectType type : all) {
                int count = bpInspectPlanRepository.countByInspectTypeId(type.getId());
                type.setCount(count);
            }
            return ResultBean.success(all);
        } else {
            Page<BpInspectType> page = bpInspectTypeRepository.findAll(pageable);
            for (BpInspectType type : page) {
                int count = bpInspectPlanRepository.countByInspectTypeId(type.getId());
                type.setCount(count);
            }
            return ResultBean.pageData(page.getContent(), page.getTotalElements());
        }
    }

}
